<template>
  <div class="browseMomentsContainer autoGrow flex-row">
    <div class="momentsGallery" v-if="currentFriend">
      <div class="subTitle">{{currentFriend.nick||currentFriend.friendnick}}的朋友圈 
        <div @click="refreshFriendTimeline" :class="{'load-icon':true, 'layui-anim-rotate layui-anim-loop':refreshing }"  style="float:right;"></div></div>
      <div class="searchMoments">
        <input type="text" class="layui-input" v-model="searchMoments" placeholder="请输入搜索关键字">
      </div>
      <div class="momentsList flex-column autoGrow">
        <div :class="['momentsItem', 'flex-column', currentMoment&&currentMoment.id==moment.id ? 'activeMoment' : '']"
          :key="index"
          @click="setCurrentMoment(moment)"
          v-for="(moment, index) in moments">
          <div class="momentsItemAuthor flex-row">
            <img :src="moment.sender.avatar" alt="" class="avatar">
            <div class="flex-column autoGrow" style="justify-content: space-around;width:100%;overflow: hidden;">
              <div class="authorName flex-row">
                <span class="textEllipsis">{{moment.sender.nick}}</span>
                <div class="buttons">
                <button class="layui-btn layui-btn-xs" v-if="momentsType!=='self'" @click.stop="forward(moment)">一键转发</button>
              </div>
              </div>
              <div class="timeline-text" v-if="moment.text" v-html="transText(moment.text)"></div>
            </div>
          </div>
          <timeline-media 
            :id="moment.id"
            :type="moment.type"
            :images="moment.imageMids"
            :mediaUrls="mediaUrls"
            :baseUrl="config.apiUrl+'/'"
            :linkTitle="moment.linkTitle"
            :linkImageURL="moment.linkImageURL"
            :linkURL="moment.linkURL"
            :linkDesc="moment.linkDesc"
            :videoContentURL="moment.videoContentURL"
            :videoPreviewURL="moment.videoPreviewURL"
            class="timeline-media"
          />
          <div class="timeline-sendtime fontGrey">
            {{formatTime(moment.createTime*1000)}}
          </div>
          <div class="timeline-interact flex-column">
            <div class="timeline-like fontGrey" v-if="moment.comments && moment.comments.length">
              点赞 <span class="like-user" v-for="(user,index) in moment.likeUsers" :key="index">{{ user.nick }} </span>
            </div>
            <div class="reply-list" v-if="moment.comments && moment.comments.length">
              <div class="reply-item" v-for="(reply) in moment.comments" :key="reply.commentId">
                <span class="reply-user">{{reply.sender.nick}}：</span>
                <span class="reply-content" v-html="transText(reply.content)"></span>
              </div>
            </div>

          </div>
          <!--  -->
        </div>
        <div v-if="!moments.length" style="text-align: center;color:#333;margin-top:200px;">
          <i v-if="!refreshing" class="layui-icon layui-icon-face-cry"></i>  
          {{ refreshing?'正在拉取朋友圈':'没有发布朋友圈 或 浏览受限' }}
        </div>
      </div>
    </div>
    <div class="opearteMoments autoGrow flex-column">
      <div class="autoGrow flex-column" v-if="currentMoment">
        <div class="subTitle">点赞</div>
        <div class="flex-row like">
          <button class="layui-btn layui-btn-sm" @click="sendLike(currentMoment,currentMoment.likeUsers.filter(item=>item.wxId===service.wxid)[0])">
            {{ currentMoment.likeUsers.filter(item=>item.wxId===service.wxid)[0]?'取消点赞':'点赞' }}
          </button>
          <span>好友点赞</span>
          <img :src="friend.avatar"
           class="friendAvatar" v-for="(friend, i) in currentMoment.likeUsers.slice(0, 5)" :key="i">
          <span>等{{currentMoment.likeUsers.length}}个好友</span>
        </div>
        <div class="comments">
          <div class="subTitle">评论</div>
          <div class="commentInput flex-row">
            <div class="commentText">
              <rich-text-editor
                placeholder="请输入要评论的内容"
                emojiPos="bottom"
                buttonText="提交"
                @submit="submitComment($event,currentMoment)"
                ref="editor"
              >
              </rich-text-editor>
            </div>
          </div>
        </div>
      </div>
    </div>
    <custom-dialog
      title="一键转发"
      wrapClass="forwardDialog"
      :closeDialog="closeDialog"
      v-if="showDialog" >
      <div class="forwardDialogContent">转发这条朋友圈，并屏蔽该好友</div>
      <template v-slot:buttons>
        <div class="flex-row dialogButtons">
         <button class="layui-btn layui-btn-xs layui-btn-normal" @click="submitForward">提交</button>
         <button class="layui-btn layui-btn-xs layui-btn-primary" @click="closeDialog">取消</button>
        </div>
      </template>
    </custom-dialog>
  </div>
</template>
<script>
import VideoPlayer from '@/components/videoPlayer'
import RichTextEditor from '@/components/richTextEditor'
import CustomDialog from '@/components/customDialog'
import TimelineMedia from '@/components/timeline-media'
import emojiParse from '@/lib/wechat-emoji'

export default {
  name: 'publishMonents',
  data() {
    return {
      showDialog: false,
      searchMoments: '',
      moments: [],
      currentMoment: null,
      forwardMoment: null,
      refreshing:false,
      timelines:{
        wxid:[]
      },
      mediaUrls:{}
    }
  },
  props: ['momentsType', 'currentService','checkedFriend'],
  mounted() {
    
  },
  components: {
    VideoPlayer,
    RichTextEditor,
    CustomDialog,
    TimelineMedia
  },
  watch:{
    currentService(newservice,oldservice){
      if(newservice[0] ){
        this.service = newservice[0]
        if( this.momentsType!='friends' ){
          this.setCurrentMoment(undefined)
          this.getFriendTimelines()
        }
      }
    },
    checkedFriend(val,oldVal){
      if(val && val!==oldVal && this.service){
        this.setCurrentMoment(undefined)
        this.getFriendTimelines()
      }
    },
    momentsType(val,oldVal){
      if(val!==oldVal){
        this.setCurrentMoment(undefined)
        this.getFriendTimelines() 
      }
    }
  },
  computed:{
    currentFriend(){
      const checkedFriend = this.checkedFriend
      const currentService = this.currentService?this.currentService[0]:undefined
      return this.momentsType=='friends'?checkedFriend:currentService
    },
     
  },
  methods: {
    
    transText(text){
      return emojiParse(text).replace(/\n/,'<br />')
    },
    forward(moment) {
      this.showDialog = true
      this.forwardMoment = moment
    },
    closeDialog() {
      this.forwardMoment = null
      this.showDialog = false
    },
    submitForward() {
      this.sendForward(this.forwardMoment)
      console.log('forward: ', this.forwardMoment)
    },
    sendLike(moment,islike){
      const { csid,wxaccount,id,friendwxid,timelineid } = moment
      const { nick,wxid,avatar } = this.service
      const params = {
        csId:csid,wxAccount:wxaccount,tid:timelineid,friendWxid:friendwxid
        // csId, wxAccount, friendWxid（为空时取当前wxAccount的全部朋友圈)，tid
      }
      this.$api.timeline.sendLike(params)
        .then(data=>{
          this.moments = this.moments.map(_moment=>{
            if(_moment.id === moment.id){
              const _likeUsers = _moment.likeUsers.filter(user=>{
                return user.wxId !== wxid
              })

              if(_likeUsers.length === _moment.likeUsers.length){
                _moment.likeUsers.push({
                  nick:nick,
                  avatar:avatar,
                  wxId:wxid
                })
              }else{
                _moment.likeUsers = _likeUsers
              }
            }
            
            return _moment
          })
          this.$msg(islike?'取消点赞成功':'点赞成功')
        })
    },

    setCurrentMoment(moment) {
      this.currentMoment = moment
    },
    submitComment(comment,moment) {
      if(comment.trim() =='')return this.$msg('请输入评论内容!')
      const { csid,wxaccount,id,friendwxid,timelineid } = moment
      const { wxid,nick,avatar } = this.service
      const params = {
        csId:csid,wxAccount:wxaccount,tid:timelineid,friendWxid:friendwxid,comment
        // csId, wxAccount, friendWxid（为空时取当前wxAccount的全部朋友圈)，tid, comment
      }
      this.$api.timeline.commentFriendLine(params)
        .then(data=>{
          const _sender = {
            avatar,
            nick,
            wxId: wxid
          }
          const _comment = {
            commentId: +new Date(),
            content:comment.trim() ,
            sender: _sender,
            senderWxId:wxid  
          }
          this.moments = this.moments.map(_moment=>{
            if(moment.id === _moment.id){
              _moment.comments.push(_comment)
            }

            return _moment
          })
          this.$msg('评论成功')
          this.$refs.editor.clear()
        })
      
    },
    replyUser(reply) {
      setTimeout(()=>{
        this.$refs.editor.setEditorValue(`@${reply.name}： `)
      },10)
    },
    requestMedia(list){
      this.$api.timeline.getTimelineFileUrls({
        mid:list.join(',')
      })
        .then(data=>{
          if(data){
            data.forEach(item=>{
              // this.mediaUrls[item.mid] = this.config.apiUrl+'/'+item.fileurl 
              this.$set(this.mediaUrls,item.mid,item.fileurl)
            })
          }
           
        })
    },
    sendForward(moment){
      const { csid,wxid } = this.service
      const {text,imageMids,type,videoContentURL,linkTitle,linkURL,linkImageURL,linkDesc,friendwxid} = moment
      let msgtype = 1,src,msg,title,content,url;

      if(type==1){
        msgtype = 2
      }else if(type == 2){
        msgtype = 1
      }else if(type == 3){
        msgtype = 10  
      }else if(type == 15){
        msgtype = 5  
      }
      msg = text||''
       
      // 2/5/10 //图片 视频 链接
      if(msgtype == 2){
        src = imageMids.map(item=>this.mediaUrls[item]).filter(item=>(item!=null))
      }else if(msgtype === 5){
        src = [videoContentURL]
      }else{
        title = linkTitle
        url = linkURL
        content = linkDesc
        src = [linkImageURL]
      }
      
      const timelineContent = {
          msgtype, //图片 视频 链接
          src, //链接的缩略图或图片地址， 组
          msg,//:"文字内容",
          //以下是卡片内容
          title,//:"",//链接标是
          content,//":"",//链接描述
          url,//:""//链接地址
          wxid:friendwxid, // 转发人用于屏蔽
      }

      const params = {
        
         wxAccount:[wxid] ,//发送帐号， 
         csId:csid , //客服ID, 
         timelineContent:JSON.stringify(timelineContent) ,//发送内容，
         sendType: 0,//0即时，1定时，
        //  sendtime: time,//定时发送时间
      }
      // console.log(params)
      this.$api.timeline.createTimeline(params)
        .then(data=>{
          this.$msg('任务创建成功')
          this.showDialog = false
          this.forwardMoment = null
        })
        .catch(e=>this.$msg(e))

    },
    getFriendTimelines(){
      if(!this.service)return
      const {csid,wxid} = this.service
      if(!wxid)return
      const momentsType = this.momentsType
      const friendWxid = momentsType=='friends'?this.checkedFriend.friendwxid:momentsType=='timeline'?'':wxid
      const params = { 
        csId:csid, 
        wxAccount:wxid, 
        friendWxid,
        pageSize:100,
        pageNo:1
      }
      this.refreshing = true
      this.$api.timeline.getFriendTimelines(params)
        .then(data=>{
          this.refreshing = false
          let fileMid = [] 
          this.moments = data.map(moment=>{
            const timelinecontent = JSON.parse(moment.timelinecontent) 
            if(timelinecontent.imageMids && timelinecontent.imageMids[0]){
              fileMid = fileMid.concat(timelinecontent.imageMids) 
            } 
            return {...moment,...timelinecontent}   
          })
          this.requestMedia(fileMid)
        }).catch((e)=>{
          this.refreshing = false
        })
    },
    refreshFriendTimeline(){
      const {csid,wxid} = this.service
      if(!wxid || this.refreshing)return
      const momentsType = this.momentsType
      const friendWxid = momentsType=='friends'?this.checkedFriend.friendwxid:wxid

      const params = { 
        csId:csid, 
        wxAccount:wxid, 
        friendWxid,
        pageSize:100,
        pageNo:1
      }
      this.$api.timeline.refreshFriendTimeline(params)
        .then(data=>{
          this.refreshing = true
          window.timelineCallback=(e)=>{
            this.refreshing = false
            this.getFriendTimelines()  
          }
        })
    }

  }
}
</script>
<style scoped>
.momentsList{
  flex:1;
  height:100%
}
.momentsContainer .browseMomentsContainer .momentsGallery{
  width: 343px
}
.momentsContainer .momentsItem{
  margin-bottom: 0;
  border-bottom: 1px solid #e1e1df
}
.momentsContainer .momentsItem .momentsItemAuthor img{
  border-radius: 3px;
  margin-right: 5px; 
}
.momentsContainer .momentsItem .momentsItemAuthor .authorName{
  color: #5b6a91;
  margin-bottom:0;
}
 
 .momentsContainer .browseMomentsContainer .momentsGallery .activeMoment{
   background:#ddd
 }
.momentsGallery{
  position: relative;
}
.load-icon{
  width:32px;
  height:32px;
  background: url("../../assets/images/rainbow.png");
  background-size: cover;

  position:absolute;
  top: 15px;
  right: 20px;

} 
.timeline-media{
  margin-top: 10px;
  margin-left: 45px;
}
.timeline-text{
  margin-top: 3px;
  line-height: 20px;
  word-break: break-all;
}
.timeline-text >>> img{
  background-color:transparent!important;
  vertical-align: middle!important;
}
.timeline-sendtime{
  margin-top: 10px;
  padding-left: 45px;
}
.timeline-interact{
  background-color: #f3f3f4;
  margin-left: 45px;
  margin-top: 10px;
  border-radius: 5px;
}
.timeline-like{
  line-height: 26px;
  padding: 0 5px;
  border-bottom: 1px solid #dddede;
  box-shadow: 0px 1px 0px #fafafa;
  font-size: 12px;
}
.like-user{
  color: #627095
}
.reply-list{

}
.reply-content >>> img{
  vertical-align: middle!important;
}
.reply-item{
  line-height: 24px;
  padding: 0 5px;
  font-size: 14px;
  color: #111111
}
.reply-user{
  color: #5b6a91
}
</style>
